<template>
  <div>
    <el-row :gutter="24">
      <el-col :span="12">
        <el-input v-model="keyword" placeholder="请输入搜索内容(30字符以内)" size="medium"
          style="margin: 0 20px 10px" @keyup.enter.native="searchChange"
          prefix-icon="el-icon-search"
        ></el-input>
      </el-col>
      <el-col :span="4" :offset="1">
          <el-tooltip content="Search" placement="top">
              <el-button type="success" icon="el-icon-search" size="medium" @click='searchChange'></el-button>
          </el-tooltip>
      </el-col>
    </el-row>
    <div style="margin-bottom: 12px;border-left: 6px solid #15a732;padding-left: 8px">
    <span style="font-size: 16px;color: #15a732">搜索明细
      <span style="fontSize: 14px">Search Detail</span>
    </span>
    </div>
    <el-table
      v-loading="loading"
      element-loading-text="正在加载..."
      ref="multipleTable"
      @selection-change="handleSelectionChange"
      :data="tableData" border
      style="width: 100%;text-align: center">
      <el-table-column
        type="selection"
        width="35">
      </el-table-column>
      <el-table-column fixed="left"
        prop="itemNum"
        label="物资编码,Item Code"
        min-width="120px" :render-header="renderHeader">
      </el-table-column>
      <el-table-column
        prop="itemDesc"
        label="物资描述,Item Description"
        min-width="260px" :render-header="renderHeader">
      </el-table-column>
      </el-table-column>
      <el-table-column
        prop="minimumOrderQuantity"
        label="最小订货量,MOQ"
        min-width="120px" :render-header="renderHeader">
      </el-table-column>
      <el-table-column
        prop="quantity"
        label="数量,Quantity"
        min-width="150"
        :render-header="renderHeader">
        <template slot-scope="scope">
          <el-input-number v-model="scope.row.quantity" controls-position="right" :step="1" :min="scope.row.minimumOrderQuantity || 1"></el-input-number>
        </template>
      </el-table-column>
      <el-table-column fixed="right"
        prop="Operation"
        label="操作,Operation"
        min-width="100px" :render-header="renderHeader">
        <template slot-scope="scope">
          <div style="text-align: center">
              <el-tooltip content="Add To The Application" placement="top">
                  <el-button @click="handleClick(scope.row,'application')" type="text"
                             size="small" class="el-icon-materials-gouwuchetianjia"></el-button>
              </el-tooltip>
              <el-tooltip content="Add To Common Materials" placement="top">
                  <el-button @click="handleClick(scope.row,'materials')" type="text"
                             size="small" class="el-icon-materials-wodedingdan"></el-button>
              </el-tooltip>


          </div>
        </template>
      </el-table-column>
    </el-table>
    <v-pagination :page-data="pageData" @onPageChange="onPageChange" v-if="!isEmpty"></v-pagination>
    <div style='width: 100%; padding: 36px 0; text-align: right'>
        <el-tooltip content="Add To The Application Form" placement="top">
            <el-button type="success" round @click="onBatch('application')">+ 加入申请单</el-button>
        </el-tooltip>
        <el-tooltip content="Add Common Material List" placement="top">
            <el-button type="primary" round style="margin-right: 36px" @click="onBatch('materials')">+ 加入常用物料</el-button>
        </el-tooltip>

    </div>
    <el-dialog title="请选择加入的分类 Please select the category to add" :visible.sync="dialogFormVisible" center width="40%"
      :close-on-click-modal="false">
      <div style="text-align: center">
        <el-cascader
          change-on-select
          :options="categoryList"
          @change="handleNodeClick">
        </el-cascader>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="onBatchMaterials(inventoryItemId)">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { materialList, batchApplication, batchMaterials, categoryList, addMaterial } from "../../../components/axios/url";
import http from "../../../components/axios/fetch";
import bus from "../../common/bus";
import {UserHelper} from "../../helpers/UserHelper";
import { ObjectUtil } from "../../../components/axios/objectUtils";
import vPagination from '../../common/Pagination.vue';
import renderHeader from '../../common/renderHeader.js';
const Cookie = require('js-cookie');

  export default {
    name: "search-list",
    data() {
      return {
        keyword: null,
        page: 1,
        tableData: [],
        isEmpty: true,
        pageData: {},
        multipleSelection: [],
        dialogFormVisible: false,
        categoryList: [],
        categoryId: null,
        inventoryItemId: null,
        loading: false
      }
    },
    props: ['applyId'],
    components:{
      vPagination
    },
    mounted() {
      const param = {
        page: this.page,
        organizationId: UserHelper.getSearchOrgId() || Cookie.get('searchOrgId')
      }
      bus.$on("tabType", (name)=>{
        if(name === 'search') {
          this.resetAll();
          this.getMaterialList(param);
        }
      });
      this.getMaterialList(param);
    },
    methods: {
      renderHeader: renderHeader,
      getMaterialList(param) { //初始方式
        this.loading = true;
        http.post(materialList, param).then(res => {
          if(res.data && res.data.resultMess === "success") {
            this.tableData = res.data.data.list;
            this.pageData = res.data.data.page;
            this.isEmpty = res.data.data.list.length === 0;
          } else {
            this.$notify.error({
              title: '提示',
              message: res.data.resultMess,
            });
          }
          this.loading = false;
        }).catch((error) => {
          this.loading = false;
          this.$notify.error({
            title: '提示',
            message: '网络错误',
          });
        })
      },
      searchChange() { //搜索
        const param = {
          page: this.page,
          keyword: this.keyword,
          organizationId: UserHelper.getSearchOrgId() || Cookie.get('searchOrgId')
        }
        this.getMaterialList(param);
      },
      onPageChange(page) { //翻页
        this.page = page;
        this.multipleSelection = [];
        const param = {
          page: page,
          keyword: this.keyword,
          organizationId: UserHelper.getSearchOrgId() || Cookie.get('searchOrgId')
        }
        this.getMaterialList(param);
      },
      handleSelectionChange(val) { //勾选事件
        this.multipleSelection = val;
      },
      onBatch(type){ //批量提交方法
        if(!this.multipleSelection.length > 0) {
          this.$notify({
            title: '提示',
            message: '请先勾选物资',
            type: 'warning'
          });
          return;
        }

        if(type === 'application') {
          const materialList = this.multipleSelection.map((item) => ({inventoryItemId: item.inventoryItemId, quantity: item.quantity}));
          const param = {applyId: this.applyId, materialListJson: JSON.stringify(materialList)};
          this.onCommonSubmit(batchApplication, param, '申请单');
        }

        if(type === 'materials') {
          this.dialogFormVisible = true;
          this.getCategoryList();
        }
      },
      async getCategoryList() { //获取分类
        const category = await http.post(categoryList,{userId: UserHelper.getUserId()});
        if(category.data && category.data.data && category.data.resultMess === "success") {
          this.categoryList = ObjectUtil.getTreeData(category.data.data.list);
        }
      },
      onBatchMaterials(inventoryItemId) { //提交常用物料弹框确定按钮事件
        if(!this.categoryId) {
          this.$message({type: 'warning', message: '请选择分类'});
          return;
        }
        if(inventoryItemId) {
          //单个提交
          this.onCommonSubmit('/category/addMaterial',{categoryId: this.categoryId, inventoryItemId} ,'常用物料', true);
          return;
        }
        //批量提交
        const ids = this.multipleSelection.map(item => item.inventoryItemId);
        this.onCommonSubmit(batchMaterials,{categoryId: this.categoryId, ids: ids.join(',')} ,'常用物料');
      },
      onCommonSubmit(postUrl, param, submitType, isSingle) {
        //公共批量提交
        http.post(postUrl, param).then(res => {
          let type, content;
          this.inventoryItemId = null;
          this.dialogFormVisible = false;
          this.categoryList = [];
          this.multipleSelection = [];
          if(res.data.resultMess === "success") {
            type = 'success';
            content = {title: '提示', message: isSingle ? `加入${submitType}成功` : `批量加入${submitType}成功`}
            this.getMaterialTotal();
          } else {
            type = 'error';
            content = {title: '提示', message: res.data.resultMess}
          }
          this.$notify[type](content);
          this.getMaterialList({page: this.page, keyword: this.keyword, organizationId: UserHelper.getSearchOrgId() || Cookie.get('searchOrgId')});
        }).catch((error) => {
          this.$notify.error({
            title: '提示',
            message: '网络错误',
          });
        })
      },
      handleNodeClick(array = []) { //批量提交常用物料弹框选中分类事件
        this.categoryId = array.slice(-1)[0];
      },
      handleClick(row,flag) {
        let submitType, postUrl, param;
        if(flag === 'application') {
          postUrl = addMaterial;
          submitType = '申请单';
          param = {applyId: this.applyId, inventoryItemId: row.inventoryItemId, quantity: row.quantity}
        }
        if(flag === 'materials') {
          this.dialogFormVisible = true;
          this.inventoryItemId = row.inventoryItemId;
          this.getCategoryList();
          return;
        }

        http.post(postUrl, param).then(res => {
          let type, content;
          if(res.data.resultMess === "success") {
            type = 'success';
            content = {title: '提示', message: `加入${submitType}成功`}
            this.getMaterialTotal();
          } else {
            type = 'error';
            content = {title: '提示', message: res.data.resultMess}
          }
          this.$notify[type](content);
          this.getMaterialList({page: this.page, keyword: this.keyword, organizationId: UserHelper.getSearchOrgId() || Cookie.get('searchOrgId')});
        }).catch((error) => {
          this.$notify.error({
            title: '提示',
            message: '网络错误',
          });
        })
      },
      getMaterialTotal: async function() { //获取加入申请单数量
        this.$emit('getMaterialTotal', null)
      },
      resetAll() {
        this.keyword = null;
        this.isEmpty = true;
        this.page = 1;
        this.tableData = [];
        this.pageData = {};
        this.multipleSelection = [];
        this.dialogFormVisible = false;
        this.categoryList = [];
        this.categoryId = null;
        this.inventoryItemId = null;
        this.loading = false
      }
    }
  }
</script>

<style scoped>
  .labelName{
    float: right;
    width: 100%;
  }
</style>
